"""
应用配置管理
使用 pydantic-settings 管理配置，从环境变量和 Python 配置文件读取
优先级: env_local.py > 环境变量 > 默认值
"""
import os
import sys
from typing import Tuple
from urllib.parse import quote_plus
from pydantic_settings import BaseSettings, SettingsConfigDict


# 尝试导入本地配置文件（如果存在）
def _load_local_config():
    """加载本地配置文件"""
    config_files = ['env_local.py', 'env_dev.py', 'env_prod.py']
    
    for config_file in config_files:
        config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), config_file)
        if os.path.exists(config_path):
            # 动态导入配置模块
            import importlib.util
            spec = importlib.util.spec_from_file_location("local_config", config_path)
            if spec and spec.loader:
                local_config = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(local_config)
                return local_config
    return None


_local_config = _load_local_config()


class Settings(BaseSettings):
    """应用配置类"""

    # 应用配置
    app_name: str = getattr(_local_config, 'APP_NAME', None) or "FaceRecognition API"
    app_version: str = getattr(_local_config, 'APP_VERSION', None) or "1.0.0"
    app_env: str = getattr(_local_config, 'APP_ENV', None) or "development"
    app_host: str = getattr(_local_config, 'APP_HOST', None) or "0.0.0.0"
    app_port: int = getattr(_local_config, 'APP_PORT', None) or 8000
    debug: bool = getattr(_local_config, 'DEBUG', None) if _local_config and hasattr(_local_config, 'DEBUG') else True

    # 数据库配置
    db_host: str = getattr(_local_config, 'DB_HOST', None) or "localhost"
    db_port: int = getattr(_local_config, 'DB_PORT', None) or 3306
    db_user: str = getattr(_local_config, 'DB_USER', None) or "root"
    db_password: str = getattr(_local_config, 'DB_PASSWORD', None) or "root123"
    db_name: str = getattr(_local_config, 'DB_NAME', None) or "facereg_db"
    db_pool_size: int = getattr(_local_config, 'DB_POOL_SIZE', None) or 10
    db_max_overflow: int = getattr(_local_config, 'DB_MAX_OVERFLOW', None) or 20

    # 人脸识别配置
    face_model_name: str = getattr(_local_config, 'FACE_MODEL_NAME', None) or "buffalo_l"
    face_model_root: str = getattr(_local_config, 'FACE_MODEL_ROOT', None) or "./models/insightface"
    face_det_size: str = getattr(_local_config, 'FACE_DET_SIZE', None) or "640,640"
    face_det_thresh: float = getattr(_local_config, 'FACE_DET_THRESH', None) or 0.5
    face_match_threshold: float = getattr(_local_config, 'FACE_MATCH_THRESHOLD', None) or 0.7
    min_face_size: int = getattr(_local_config, 'MIN_FACE_SIZE', None) or 80

    # FAISS索引配置
    faiss_index_path: str = getattr(_local_config, 'FAISS_INDEX_PATH', None) or "./data/faiss_index/face_index.bin"
    faiss_dimension: int = getattr(_local_config, 'FAISS_DIMENSION', None) or 512

    # 日志配置
    log_level: str = getattr(_local_config, 'LOG_LEVEL', None) or "INFO"
    log_path: str = getattr(_local_config, 'LOG_PATH', None) or "./logs"

    # Pydantic配置 (保留环境变量支持)
    model_config = SettingsConfigDict(
        case_sensitive=False,
        extra="ignore"
    )

    @property
    def database_url(self) -> str:
        """构建数据库连接URL（自动处理密码中的特殊字符）"""
        # 对用户名和密码进行URL编码，处理特殊字符（如 @, :, / 等）
        encoded_user = quote_plus(self.db_user)
        encoded_password = quote_plus(self.db_password)
        return f"mysql+pymysql://{encoded_user}:{encoded_password}@{self.db_host}:{self.db_port}/{self.db_name}?charset=utf8mb4"

    @property
    def face_det_size_tuple(self) -> Tuple[int, int]:
        """解析人脸检测尺寸"""
        w, h = self.face_det_size.split(',')
        return int(w), int(h)


# 全局配置实例
settings = Settings()
